﻿<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Uploader.ascx.cs" Inherits="UserControls_Uploader" %>

<asp:Panel ID="UploaderPanel" runat="server" CssClass="uploaderElement">		
	<noscript>			
		<p>Please enable JavaScript to use file uploader.</p>
		<!-- or put a simple form for upload here -->
	</noscript>         
</asp:Panel>
<asp:Panel ID="FilesPanel" runat="server" CssClass="loadedFiles">
    <asp:Repeater runat="server" ID="FilesRepeater" 
        OnItemDataBound="FilesRepeater_ItemDataBound" >
        <HeaderTemplate>
            <table width="440" border="0" cellpadding="0" cellspacing="0" class="dataTable">
                <col width="100" />
                <col width="50" />
                <col width="290" />
                <thead>
                    <tr class="header">
                        <th colspan="2">&nbsp;</th>
                        <th>Nombre del Archivo</th>
                    </tr>
                </thead>
                <tbody>    
        </HeaderTemplate>
        <ItemTemplate>
            <tr class="item0">
                <td>
                    <asp:HyperLink ID="DeleteButton" runat="server" Text="Eliminar archivo" NavigateUrl="#" CssClass='<%# ClientID + "_DeleteFile" %>'></asp:HyperLink>
                </td>
                <td>
                    <asp:HyperLink ID="DownloadButton" runat="server" Text="Descargar" NavigateUrl="#" CssClass='<%# ClientID + "_DownloadFile" %>'></asp:HyperLink>
                </td>
                <td>
                    <asp:Label Text="<%# Bind('NombreArchivo') %>" runat="server" ID="FileNameLabel" />
                    <asp:Label ID="ArchivoIdHiddenLabel" runat="server" Visible="false" Text="<%# Bind('ArchivoId') %>"></asp:Label>
                </td>
            </tr>
        </ItemTemplate>
        <AlternatingItemTemplate>
            <tr class="item1">
                <td>
                    <asp:HyperLink ID="DeleteButton" runat="server" Text="Eliminar archivo" NavigateUrl="#" CssClass='<%# ClientID + "_DeleteFile" %>'></asp:HyperLink>
                </td>
                <td>
                    <asp:HyperLink ID="DownloadButton"  runat="server" Text="Descargar" NavigateUrl="#" CssClass='<%# ClientID + "_DownloadFile" %>'></asp:HyperLink>
                </td>
                <td>
                    <asp:Label Text="<%# Bind('NombreArchivo') %>" runat="server" ID="FileNameLabel" />
                    <asp:Label ID="ArchivoIdHiddenLabel" runat="server" Visible="false" Text="<%# Bind('ArchivoId') %>"></asp:Label>
                </td>
            </tr>
        </AlternatingItemTemplate>
        <FooterTemplate>
                    <tr class="item0 empty" runat="server" id="emptyTemplate" visible="<%# bool.Parse((FilesRepeater.Items.Count == 0).ToString()) %>">
                        <td colspan="3" align="center">
                            No existen archivos cargados en el sistema
                        </td>
                    </tr>
                </tbody>
            </table>
        </FooterTemplate>
    </asp:Repeater>
</asp:Panel>

<asp:HiddenField ID="SelectedFileIdsHiddenField" runat="server" Value="[]" />
<asp:HiddenField ID="DeletedFileIdsHiddenField" runat="server" Value="[]" />
<asp:HiddenField ID="TipoRelacionHiddenField" runat="server" Value="General" />
<asp:HiddenField ID="ObjetoIdHiddenField" runat="server" Value="0" />
<asp:HiddenField ID="MaxFilesToUploadHiddenField" runat="server" Value="1" />
<asp:HiddenField ID="FileIdToDownloadHiddenField" runat="server" Value="0" />
<asp:HiddenField ID="ModeHiddenField" runat="server" Value="Insert" />
<asp:HiddenField ID="DonwloadAsHiddenField" runat="server" Value="Action" />

<asp:LinkButton ID="DownloadButton" runat="server" OnClick="DownloadButton_Click" style="display:none">.</asp:LinkButton>
<asp:Panel ID="DialogConfirmPanel" runat="server"
    ToolTip="Mensaje de Confirmacion">
    <p>
        <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
        <asp:Literal ID="MessageLiteral" runat="server"
            Text="¿Esta seguro que desea eliminar el archivo seleccionado?.">
        </asp:Literal>
    </p>
</asp:Panel>
<div style="display:none;" id="temp" runat="server"></div>
<script type="text/javascript">
    var <%= ClientID %>_button = false;
    var <%= ClientID %>_fileId = 0;
    var <%= ClientID %>_files = new Array();
    var <%= ClientID %>_deletedFiles = new Array();
    var <%= ClientID %>_downloadCounter = 0;
    $(document).ready(function(){
        $("#aspnetForm").attr("target","_self");
        $("#<%= DialogConfirmPanel.ClientID %>").dialog({
            resizable: false,
            height: 180,
            modal: true,
            autoOpen: false,
            buttons: {
                'Si': function () {
                    <%= ClientID %>_deleteFile();
                    $(this).dialog('close');
                },
                'No': function () {
                    $(this).dialog('close');
                }
            }
        });

        $(".<%= ClientID %>_DeleteFile").live("click",function(){
            <%= ClientID %>_button = $(this);
            <%= ClientID %>_fileId = $(this).attr("FileId");
            $("#<%= DialogConfirmPanel.ClientID %>").dialog("open");            
            return false;
        });

        $(".<%= ClientID %>_DownloadFile").live("click",function(){
            var archivoId = $(this).attr("FileId");
            <%= ClientID %>_downloadCounter = 0;
            if($("#<%= DonwloadAsHiddenField.ClientID %>").val() == "Action"){
                $("#<%= FileIdToDownloadHiddenField.ClientID %>").val(archivoId);
                eval($("#<%= DownloadButton.ClientID %>").attr("href"));
            }else{
                $("#<%= temp.ClientID %>").load('<%= RegiterInSessionHandler %>?KeY=FILE_ID&vAlUe=' + archivoId, function(){
                    <%= ClientID %>_downloadCounter++;
                    if(<%= ClientID %>_downloadCounter == 1)
                        open("<%= OpenFilePage %>");
                });
                
            }
            return false;
        });
        var max = parseInt($("#<%= MaxFilesToUploadHiddenField.ClientID %>").val());
        if($("#<%= FilesPanel.ClientID %> tbody tr").not(".empty").length >= max){
            $("#<%= UploaderPanel.ClientID %>").hide();
        }else{
            $("#<%= UploaderPanel.ClientID %>").show();
        }
//        $("#<%= UploaderPanel.ClientID %> .btnUpload input").css("position","fixed");
//        $("#<%= UploaderPanel.ClientID %> .btnUpload input").css("opacity","1");
//        $("#<%= UploaderPanel.ClientID %> .btnUpload").mousemove(function(e){
//            $("#<%= UploaderPanel.ClientID %> .btnUpload input").css({
//                left: e.clientX-$("#<%= UploaderPanel.ClientID %> .btnUpload input").width() + 20,
//                top: e.clientY-5 
//            });
//        });
//        $("#<%= UploaderPanel.ClientID %> .btnUpload").mouseout(function(e){
//            $("#<%= UploaderPanel.ClientID %> .btnUpload input").css({
//                left: 0,
//                top: 0
//            });
//        });
    });
<% if (Mode != ModeControl.Readonly){ %>
    var <%= ClientID %>_uploader = new qq.FileUploader({
        element: document.getElementById('<%= UploaderPanel.ClientID %>'),
        action: '<%= UploaderHandler %>',
        template: '<div class="qq-uploader">' +
                '<div class="qq-upload-drop-area">Arrastre y suelte su archivo aqui para cargarlo</div>' +
                '<a class="btnUpload"><span><asp:Literal ID="UploadButtonLiteral" runat="server" Text="Cargar archivo"></asp:Literal><span></a>' +
                '<ul class="qq-upload-list"></ul>' +
                '</div>',
        allowedExtensions: <%= ExtensionAllowed %>,
        onComplete: function (id, fileName, responseJSON) {
            if (!responseJSON || !responseJSON.Success) {
                return;
            }
            <%= ClientID %>_files[<%= ClientID %>_files.length] = responseJSON.ArchivoId;
            $("#<%= SelectedFileIdsHiddenField.ClientID %>").val(JSON.stringify(<%= ClientID %>_files));
            $("#<%= FilesPanel.ClientID %> tbody tr.empty").remove();
            $("#<%= FilesPanel.ClientID %> tbody").append(<%= ClientID %>_GetNewElementForFile(responseJSON.ArchivoId, responseJSON.FileName));

            var max = parseInt($("#<%= MaxFilesToUploadHiddenField.ClientID %>").val());

            if($("#<%= FilesPanel.ClientID %> tbody tr").not(".empty").length >= max){
                $("#<%= UploaderPanel.ClientID %>").hide();
            }else{
                $("#<%= UploaderPanel.ClientID %>").show();
            }
        },
        classes: {
            // used to get elements from templates
            button: 'btnUpload',
            drop: 'qq-upload-drop-area',
            dropActive: 'qq-upload-drop-area-active',
            list: 'qq-upload-list',
            file: 'qq-upload-file',
            spinner: 'qq-upload-spinner',
            size: 'qq-upload-size',
            cancel: 'qq-upload-cancel',
            // added to list item when upload completes
            // used in css to hide progress spinner
            success: 'qq-upload-success',
            fail: 'qq-upload-fail'
        }
    });

<% } %>
    function <%= ClientID %>_GetNewElementForFile(fileId, fileName){
        var i = ($("#<%= FilesPanel.ClientID %> tbody tr").length + 1) % 2;
        return  '<tr class="item'  + i + '">' + 
                    '<td><a href="#" FileId="' + fileId + '" class="<%= ClientID %>_DeleteFile">Eliminar archivo</a></td>' + 
                    '<td><a href="#" FileId="' + fileId + '" class="<%= ClientID %>_DownloadFile">Descargar</a></td>' + 
                    '<td><span>' + fileName + '</span></td>' +
                '</tr>';
    }

    function <%= ClientID %>_deleteFile(){
        if($("#<%= ModeHiddenField.ClientID %>").val() == "Insert"){
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%= DeleteHandler %>?archivoId=' + <%= ClientID %>_fileId,
                dataType: "json",
                success: function(result) {
                    if(result){
                        <%= ClientID %>_deleteElementAfterDelete();
                    }
                }
            });
        }else if($("#<%= ModeHiddenField.ClientID %>").val() == "Edit"){
            <%= ClientID %>_deletedFiles[<%= ClientID %>_deletedFiles.length] = <%= ClientID %>_fileId;
            $("#<%= DeletedFileIdsHiddenField.ClientID %>").val(JSON.stringify(<%= ClientID %>_deletedFiles));
            <%= ClientID %>_deleteElementAfterDelete();
        }
    }

    function <%= ClientID %>_deleteElementAfterDelete(){
        $(<%= ClientID %>_button).parent().parent().remove();
        $("#<%= FilesPanel.ClientID %> tbody tr").removeAttr("class");
        var trs = $("#<%= FilesPanel.ClientID %> tbody tr");
        for (var i = 0; i < trs.length; i++) {
            $(trs[i]).attr("class","item" + (i%2));
        }
        var max = parseInt($("#<%= MaxFilesToUploadHiddenField.ClientID %>").val());
        var aux = new Array();
        for(var i = 0; i < <%= ClientID %>_files.length ; i++){
            if(<%= ClientID %>_files[i] != <%= ClientID %>_fileId)
                aux[aux.length] = <%= ClientID %>_files[i];
        }
        <%= ClientID %>_files = aux;
        $("#<%= SelectedFileIdsHiddenField.ClientID %>").val(JSON.stringify(<%= ClientID %>_files));
        if($("#<%= FilesPanel.ClientID %> > div").length >= max){
            $("#<%= UploaderPanel.ClientID %>").hide();
        }else{
            $("#<%= UploaderPanel.ClientID %>").show();
        }
        <%= ClientID %>_setEmptyTemplate();
        <%= ClientID %>_button = false;
        <%= ClientID %>_fileId = 0;
    }

    function <%= ClientID %>_setEmptyTemplate(){
        if($("#<%= FilesPanel.ClientID %> tbody tr").length > 0)
            return;

        var emptyTemplate = 
            '<tr class="item0 empty">' +
                '<td colspan="3" align="center">No existen archivos cargados en el sistema</td>' + 
            '</tr>';
        $("#<%= FilesPanel.ClientID %> tbody").html(emptyTemplate);
    }

    function <%= ClientID %>_getInsertedFile(){
        return $("#<%= SelectedFileIdsHiddenField.ClientID %>").val();
    }
</script><%--
$("#<%= FileNameLabel.ClientID %>").html(responseJSON.FileName);
            $("#<%= DeleteButton.ClientID %>").attr("fileId", responseJSON.ArchivoId);
            $("#<%= FilesPanel.ClientID %>").show();
            $("#<%= UploaderPanel.ClientID %>").hide();--%>